package vrp;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import java.util.Date;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import vrp.PMF;
import vrp.SaleOrder;
import vrp.Delivery;
import vrp.Product;

public class DeliveryAddServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {

    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	DateFormat df = new SimpleDateFormat ("yyyy-MM-dd");

    	long saleOrderID = Integer.parseInt(req.getParameter("saleOrder"));
    	long partnerID = Integer.parseInt(req.getParameter("client"));
        try {
            Key saleOrderKey = KeyFactory.createKey(SaleOrder.class.getSimpleName(), saleOrderID);
            SaleOrder saleOrder = pm.getObjectById(SaleOrder.class, saleOrderKey);

            Key customerKey = saleOrder.getCustomer();
            Key productKey = saleOrder.getProduct();
            Product product = pm.getObjectById(Product.class, productKey);
            int inventory = product.getInventory();
            int quantity = saleOrder.getQuantity();
            int recurringType = saleOrder.getRecurringType();
            Date deliveryDate = saleOrder.getNextDeliveryDate();
            Date endDate = saleOrder.getEndDate();
            
            if (inventory < quantity) {
            	pm.close();
            	resp.sendRedirect("/saleorders.jsp?error=inventory");
            	return;
            }
            Delivery delivery = new Delivery(saleOrderKey, customerKey, productKey, quantity, deliveryDate);
            pm.makePersistent(delivery);
            
            product.setInventory(inventory-quantity);
            pm.makePersistent(product);
            
            if (recurringType>0){
            	//calculate newDeliveryDate
	            String dateString = df.format(deliveryDate);
	            String[] dateStringParts = dateString.split("-");
	            Calendar calendar = Calendar.getInstance();
	            calendar.set(Integer.parseInt(dateStringParts[0]),Integer.parseInt(dateStringParts[1])-1,Integer.parseInt(dateStringParts[2]),0,0);
	            calendar.add(Calendar.DATE, recurringType);
	            Date newDeliveryDate = calendar.getTime();
	            if (newDeliveryDate.after(endDate)) {
	            	saleOrder.setStatus(1); //DONE
	            } else {
		            saleOrder.setNextDeliveryDate(newDeliveryDate);
	            }
            } else {
            	saleOrder.setStatus(1); //DONE
            }
            saleOrder.setModifiedAt(new Date());
            pm.makePersistent(saleOrder);
        } finally {
            pm.close();
        }
        resp.sendRedirect("/saleorders.jsp?client=" + partnerID);
    }
}